import axios from 'axios'
import {
  MessageBox,
  Message
} from 'element-ui'
import store from '@/store'
import {
  getToken,
  setToken,
  removeToken
} from "@/utils/auth";
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  // timeout: 10000, // 请求超时
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    let hasToken = store.getters.token;
    // console.log("request-hasToken", hasToken)
    // console.log("localStorage.fnhToken", localStorage.fnhToken)
    if (hasToken == undefined && localStorage.fnhToken != undefined) {
      hasToken = localStorage.fnhToken;
    }
    if (hasToken) {
      // 让每个请求携带令牌
      // [X 令牌]是自定义标头键
      // 请根据实际情况修改
      // config.headers['X-Token'] = getToken()
      //新赋能是token;赋能惠看板是JWT
      config.headers['Authorization'] = " JWT " + hasToken //获取token并添加至请求头内
    }
    return config
  },
  error => {

    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截器
/**
 * 如果要获取 http 信息，如标头或状态
 * 请 return  response => response
 */

/**
 * 通过自定义代码确定请求状态
 * 这里只是一个例子
 * 您还可以通过 HTTP 状态代码判断状态
 */
service.interceptors.response.use(response => {
    const res = response.data
    // 如果自定义代码不是 20000，则判断为错误。

    return response.data

  },
  error => {
    console.log('err' + error) // for debug
    // if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1) {
    //   console.log('根据你设置的timeout/真的请求超时 判断请求现在超时了，你可以在这里加入超时的处理方案')
    //   Message({
    //     message: '网络卡爆了,我也不知道咋办!',
    //     type: 'error',
    //     duration: 10 * 1000
    //   })
    // }
    //  2.需要重定向到错误页面
    const errorInfo = error.response
    console.log("errorInfo", errorInfo)
    if (errorInfo) {
      if (errorInfo.status === 401) {
        Message({
          // message: error.message,
          message: `登录信息已过期,请重新登录!`,
          type: 'error',
          duration: 10 * 1000
        })
        localStorage.fnhToken = "";
        removeToken()
        router.push({
          path: "/login"
        });
        return;
      } else if (errorInfo.status === 403) {
        Message({
          // message: error.message,
          message: `${errorInfo.status}!请重新登录!`,
          type: 'error',
          duration: 10 * 1000
        })
        localStorage.fnhToken = "";
        removeToken()
        router.push({
          path: "/login"
        });
      } else if (errorInfo.status == 500) {
        Message({
          // message: error.message,
          message: `服务器异常${errorInfo.status}!请联系程序员小哥哥!`,
          type: 'error',
          duration: 10 * 1000
        })
      }
    }
    return Promise.reject(error)
  }
)

export default service
